/*
 * MIT License
 *
 * Copyright (c) 2024 恩爸编程
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.enba.boot.encrypt.strategy;

import com.enba.boot.encrypt.properties.EncryptionProperties;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("aesEncryptionService")
public class AesEncryptionStrategy implements EncryptionStrategy {

  private static final String ALGORITHM = "AES";
  private static final String TRANSFORMATION =
      "AES/CBC/PKCS5Padding"; // Specify transformation including mode and padding
  private static final int IV_SIZE = 16; // AES block size is 16 bytes

  private final SecretKeySpec secretKey;

  @Autowired
  public AesEncryptionStrategy(EncryptionProperties encryptionProperties) throws Exception {
    byte[] keyBytes = Base64.getDecoder().decode(encryptionProperties.getKey());
    this.secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
  }

  @Override
  public String encrypt(String data) throws Exception {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);

    // Generate a random IV for each encryption operation
    byte[] ivBytes = new byte[IV_SIZE];
    SecureRandom random = new SecureRandom();
    random.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));

    // Combine IV and encrypted data
    byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
    System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
    System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

    return Base64.getEncoder().encodeToString(combined);
  }

  @Override
  public String decrypt(String encryptedData) throws Exception {
    byte[] combined = Base64.getDecoder().decode(encryptedData);

    // Extract the IV from the beginning of the combined data
    byte[] ivBytes = new byte[IV_SIZE];
    System.arraycopy(combined, 0, ivBytes, 0, ivBytes.length);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    // Extract the encrypted data
    byte[] encryptedBytes = new byte[combined.length - ivBytes.length];
    System.arraycopy(combined, ivBytes.length, encryptedBytes, 0, encryptedBytes.length);

    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

    return new String(decryptedBytes, "UTF-8");
  }
}
